<template>
  <div>
    <InfiniteScroll
      :size="paragraph_list.length"
      :total="modelValue.length"
      :page_size="page_size"
      v-model:current_page="current_page"
      @load="next()"
      :loading="loading"
    >
      <el-card
        v-for="(child, cIndex) in paragraph_list"
        :key="cIndex"
        shadow="never"
        class="card-never mb-16"
        @click="paragraphClick($event, cIndex)"
      >
        <div class="flex-between">
          <span> <el-checkbox v-if="editMode" :model-value="cSelect[cIndex]" /> {{ child.title || '-' }}</span>
          <div>
            <!-- 编辑分段按钮 -->
            <el-button link @click="editHandle(child, cIndex)">
              <el-icon><EditPen /></el-icon>
            </el-button>
            <!-- 删除分段按钮  -->
            <el-button link @click="deleteHandle(child, cIndex)">
              <el-icon><Delete /></el-icon>
            </el-button>
          </div>
        </div>
        <div class="lighter mt-12">
          {{ child.content }}
        </div>
        <div class="lighter mt-12">
          <el-text type="info">
            {{ child.content.length }} {{ $t('views.paragraph.character_count') }}
          </el-text>
        </div>
      </el-card>
    </InfiniteScroll>

    <EditParagraphDialog
      ref="EditParagraphDialogRef"
      @updateContent="updateContent"
      :isConnect="isConnect"
    />
  </div>
</template>
<script setup lang="ts">
import { cloneDeep } from 'lodash'
import { ref, computed } from 'vue'
import EditParagraphDialog from './EditParagraphDialog.vue'
import { MsgConfirm } from '@/utils/message'
import { t } from '@/locales'
const page_size = ref<number>(30)
const current_page = ref<number>(1)
const currentCIndex = ref<number>(0)
const EditParagraphDialogRef = ref()
const emit = defineEmits(['update:modelValue', 'update:combinable'])
const loading = ref<boolean>(false)
const editHandle = (item: any, cIndex: number) => {
  currentCIndex.value = cIndex
  EditParagraphDialogRef.value.open(item)
}

const props = withDefaults(defineProps<{
  modelValue: Array<any>; isConnect: boolean;
  editMode: boolean; combinable: boolean
}>(), {
  editMode: false,
  combinable: false
})

const selectedParagraph = ref<Array<number>>([]);

const cSelect = computed(() => {
  let selected = Array<boolean>()
  if (selectedParagraph.value.length > 0) {
    selected[selectedParagraph.value[0]] = true;
  }
  if (selectedParagraph.value.length > 1) {
    for (let idx:number = selectedParagraph.value[0] + 1; idx <= selectedParagraph.value[1]; idx++ ) {
      selected[idx] = true;
    }
  }
  return selected
})

const paragraph_list = computed(() => {
  return props.modelValue.slice(0, page_size.value * (current_page.value - 1) + page_size.value)
})

const paragraphClick = (item: any, cIndex: number) => {
  if (!props.editMode) return
  if (selectedParagraph.value.length === 0) {
    selectedParagraph.value = [cIndex]
    emit('update:combinable', false)
  } else {
    if (cIndex < selectedParagraph.value[0]) {
      selectedParagraph.value = [cIndex]
      emit('update:combinable', false)
    } else {
      if (selectedParagraph.value.length === 1 && selectedParagraph.value[0] !== cIndex) {
        selectedParagraph.value = [selectedParagraph.value[0], cIndex]
        emit('update:combinable', true)
      } else {
        selectedParagraph.value = [cIndex]
        emit('update:combinable', false)
      }
    }
  }
}

const next = () => {
  loading.value = true
  current_page.value += 1
  loading.value = false
}

const updateContent = (data: any) => {
  const new_value = [...props.modelValue]
  if (
    props.isConnect &&
    data.title &&
    !data?.problem_list.some((item: any) => item.content === data.title.trim())
  ) {
    data['problem_list'].push({
      content: data.title.trim()
    })
  }
  new_value[currentCIndex.value] = cloneDeep(data)
  emit('update:modelValue', new_value)
}

const deleteHandle = (item: any, cIndex: number) => {
  MsgConfirm(
    `${t('views.paragraph.delete.confirmTitle')}${item.title || '-'} ?`,
    t('views.paragraph.delete.confirmMessage'),
    {
      confirmButtonText: t('common.confirm'),
      confirmButtonClass: 'danger'
    }
  )
    .then(() => {
      const new_value = [...props.modelValue]
      new_value.splice(cIndex, 1)
      emit('update:modelValue', new_value)
    })
    .catch(() => {})
}

const combineParagraph = ()=>{
  const new_value = [...props.modelValue]
  let startIdx: number = selectedParagraph.value[0]
  let endIdx: number = selectedParagraph.value[1] + 1
  let title:string = props.modelValue[startIdx].title;
  let contentList: Array<string> = [props.modelValue[startIdx].content]
  for (let i = startIdx+1; i < endIdx; i++) {
    let paragraph = props.modelValue[i]
    let pTitle = paragraph.title.trim()
    let pContent = paragraph.content.trim()
    if (pTitle){
      contentList.push(pTitle)
    }
    if (pContent){
      contentList.push(pContent)
    }
  }
  let newParagraph = {
    title: title,
    content: contentList.join('\n'),
  }
  new_value.splice(startIdx, endIdx - startIdx, newParagraph);
  emit('update:modelValue', new_value)
  emit('update:combinable', false)
  selectedParagraph.value = []
}

defineExpose({ combineParagraph })

</script>
<style lang="scss" scoped></style>
